// import { TInput,TPopupProxy ,TInnerLoading,TBreadcrumbs} from 't';
import TInput from 't/basic/input';
import TButton from 't/basic/button'
import TPopupProxy from 't/basic/popup-proxy';
import TInnerLoading from 't/basic/inner-loading';
import TBreadcrumbs from 't/basic/breadcrumbs';
import TDialog from 't/basic/dialog';
import TCard from 't/basic/card';
import TMenu from 't/basic/menu';
import TList from 't/basic/list';
import TItem from 't/basic/item';
import TItemSection from 't/basic/item-section';
import TCardSection from 't/basic/card/CardSection';
import TCardActions from 't/basic/card/CardActions';
import TTable from 't/basic/table';
import TTd from 't/basic/table/Td';
import TTh from 't/basic/table/Th';
import TCheckbox from 't/basic/checkbox';
import {
  commonProps,
  fixNameSpace,
  pickOwnForBasicComponent
} from 't/common/utils';
import './selectHelperJS'
import {
  computed,
  defineComponent, onMounted, onUnmounted, nextTick,ref
} from 'vue';
import { useDisplayingResults, useGenerateInput } from './Composables/useDisplayingResults';
import { useIcon } from './Composables/useIcon';
import { useRenderContent } from './Composables/useRenderContent';
import { useUtils } from './Composables/useUtils';
import { useWatch } from './Composables/useWatch';
import './style.scss';

export default defineComponent({
  name: fixNameSpace('select-tree-helper'),
  components: {
    TInput,TPopupProxy,TInnerLoading,TBreadcrumbs,TButton,TDialog,TCard,TMenu,TList,TItem,TItemSection,TCardSection,TCardActions,TTable,TTd,TTh,TCheckbox
  },
  props: {
    ...commonProps,
    demo: {
      type: String,
      default() {
        return '';
      },
    },
    simple: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    height: {
      type: String,
    },
    position: {
      type: String,
      default: 'bottom',
    },
    historyEnable: {
      type: Boolean,
      default: false,
    },
    dropDownWidth: {
      type: String,
      default: 'auto',
    },
    dropDownWidthStatic: {
      type: String,
      default: '500px',
    },

    search: Function,
    confirm: Function,
    historySaveCount: Number,
    isSingle: Boolean,
    label: String,
    labelField: String,
    lazy: Boolean,
    pagination: Boolean,
    placeholder: String,
    onClear: Function,
    onOpen: Function,
    onOpening: Function,
    title: String,
    value: {
      type: Array || String,
    },
    valueField: String,
    helperCode: String,
    subsidiary: {
      require: false,
      default: '',
      type: String,
    },
    helpConf: Boolean,
    helpTooltip: String,
    required: Boolean,
    helpPlacement: String,
    helpMorePopup: String,
    helpMoreLinkHrefStatic: String,
    helpMoreLinkHrefExp: String,
    readonly: Boolean,
    readOnly: Boolean,
    isDev: Boolean,
    opening: Function,
    openType: String,
    countPerPage: {
      type: Number,
      default: 10,
    },
    searchEnable: {
      default: true,
      type: Boolean,
    },
    visible: {
      default: true,
      type: Boolean,
    },
    showChecked: {
      default: true,
      type: Boolean,
    },
    searchPosition: {
      default: 'top',
      type: String,
    },
    icon: String,
    unit: String,
    maxCheckedLength: {
      type: [String, Number],
      default:''
    },
    hideLabel: {
      type: Boolean,
      default: false,
    },
    text: {
      type: String || Array,
      default: false,
    },
    borderType:String,

    columns: Array,
    labelPosition: String,
    rules: Array,
    iconEnable: Boolean,
    iconDataSource: String,
    iconFiled: String,
    pageid: String,
    instanceCode: String,
    /***********新增属性******** */
    customResults_result:[String,Array],
    relationIcon:String,
    indent:String,
    childNodeName:String,
    leaf:String,
    leafValue:String,
    isLazy:Boolean,
    openIcon:String,
    foldIcon:String,
    onlyCheckedNotLeaf:Boolean,
    linker:String,
    showSequence:String,
    responseRelationNode:Boolean,
    type:[Number,String],
    value_pid:String,
    lable_pid:String,
    noData:String,
    classiFicationCode:String,
    customResults:[String,Array],
    parentId:[String,Number],
    classiFicationStepRule:String,
    classiFicationStep:String,
    isClassiFicationSteps:Boolean,
    customIcons:String,
    iconField1:String,
    showIconField1:String,
    showIconField:String,
    customIcon:String,
    forcedAssociation:String,
    leafValue_custom:String,
    isLeaf:String,
    modelValue:[String,Array],
    displayDataSource:String,
    displayMapping:String,
    valueMapping:Object,
    record: {
      type: Object,
      default: null
    },
    localvars:{
      type:Object,
      default:()=>{
        return window.LocalVars
      }
    },
    disable:{
      type:Boolean,
      default:()=>{
        return false
      }
    }
  },
  emits: ['confirm','update:value','update:text'],

  setup(props, { attrs, emit, expose, slots }) {
    //构建变量
    const PropsMapping = useUtils(props,emit);
    // 将 record 传递给 PropsMapping
    if (props.record) {
      PropsMapping.record.value = props.record;
    }
    let clientHeight = window.innerHeight+'px';
    document.documentElement.style.setProperty('--t-client-height', clientHeight);
    window.addEventListener('resize', function(event) {
      clientHeight = window.innerHeight+'px';
      document.documentElement.style.setProperty('--t-client-height', clientHeight);

  });

    // 添加 postMessage 支持，用于接收外部传递的 options
    const handlePostMessage = (event) => {
      if (event.data && event.data.type === 'treeSelectHelperOptions') {
        console.log('select-tree-helper 接收到 options:', event.data.payload);
        const { options, requestId } = event.data.payload;

        // 将接收到的 options 传递给组件内部使用
        if (PropsMapping.selectTreeHelperContent && PropsMapping.selectTreeHelperContent.value) {
          // 如果组件已经初始化，直接更新 options
          PropsMapping.selectTreeHelperContent.value.updateOptions(options);
        } else {
          // 如果组件还未初始化，存储 options 供后续使用
          PropsMapping.externalOptions = options;
        }
      }
    };

    // 在组件挂载时添加 postMessage 监听
    onMounted(() => {
      window.addEventListener('message', handlePostMessage);
    });

    // 在组件卸载时移除监听
    onUnmounted(() => {
      window.removeEventListener('message', handlePostMessage);
    });

    //注册watch事件
    useWatch(PropsMapping);
    const { refField, FieldWidth, fieldValue, mappingProps, mappingExpose } = PropsMapping

    const text = computed(() => {
      let getDisplayingResults = PropsMapping.getDisplayingResults.value
      if(mappingProps.multiple){
        if(getDisplayingResults){
          return getDisplayingResults.map(item=>item[mappingProps.labelField]).join(',')
        }
        return ''
      }
      return getDisplayingResults
    })
    const isShow = ref(false)
    const autoFocus = ref(false)
    expose({
      ...mappingExpose,
      text,
      focus:()=>{
        autoFocus.value=true
        PropsMapping.select_tree_helper_input.value&&(autoFocus.value=false)
        PropsMapping.select_tree_helper_input.value&&PropsMapping.select_tree_helper_input.value.click()
      },
      validate:()=>{
      return refField.value?.validate(...arguments)
      },
      resetValidation:()=>{
        return refField.value?.resetValidation(...arguments);
      },
      isShow
    })
    onMounted(async()=>{
      await nextTick()
      if(autoFocus.value){
        PropsMapping.select_tree_helper_input.value&&(autoFocus.value=false)
        PropsMapping.select_tree_helper_input.value&&PropsMapping.select_tree_helper_input.value.click()
      }
    })
    let disable = computed(() => {
      let db = mappingProps.disable || mappingProps.disabled;
      let shouldSetBgColor = db;
      return {
        bgColor: shouldSetBgColor ? '#f1f1f1' : mappingProps.bgColor,
        disable: db,
      };
    });
    return () => {
      return (
          <t-input
          class={[
            (mappingProps.disable || mappingProps.disabled) &&
            'tr-input-disabled',
          ]}
          {...disable.value}
            {...pickOwnForBasicComponent(mappingProps, TInput.props)}
            stack-label
            clearable={false}
            v-model:modelValue={PropsMapping.displayingResults.value}
            ref={refField}
            class='select_tree_helper_input tr-input-form'
            labelPosition={mappingProps.labelPosition}
            borderType='borderless'
            rules={mappingProps.rules}
          >
            {{
              prepend: () => {
                return (
                  <div
                    style={`gap:8px;position:relative;font-size:12px;color: rgba(0, 0, 0, var(--t-color-opacity, /*批量处理90%透明度*/0.9));${fieldValue.value ? 'padding-left:6px' : ''};width:100%;display:flex;align-items:center;${mappingProps.multiple ? 'flex-wrap:wrap' : ''}`}
                    onClick={(e) => {
                      e.stopPropagation();
                      e.preventDefault();
                      return false;
                    }}
                 >
                    {useDisplayingResults(PropsMapping,emit,isShow)}
                    {useGenerateInput(PropsMapping)}
                  </div>
                );
              },
              default: () => {

                return (mappingProps.readonly||mappingProps.readOnly||mappingProps.isDev)?'':useRenderContent(PropsMapping,emit,isShow,refField);
              },
              append: () => {
                return mappingProps.readOnly?'': useIcon(PropsMapping);
              },
            }}
          </t-input>
      );
    };
  },
});
